package com.cn.codebrush.字符串;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Author Boolean
 * @Date 2022/5/27 22:29
 * @Version 1.0
 */
public class 面试题1711单词距离 {
    public static void main(String[] args) {
        String[] words = {"I","am","a","student","from","a","university","in","a","city"};
        String word1 = "a";
        String word2 = "student";
        System.out.println(findClosest(words,word1,word2));
    }


    public static int findClosest(String[] words, String word1, String word2) {
        int n = words.length;
        Map<String, List<Integer>> map = new HashMap<>();
        for(int i=0;i<n;i++){
            if(words[i].equals(word1)){
                if(map.containsKey(word1)){
                    map.get(word1).add(i);
                }else {
                    List list = new ArrayList<>();
                    list.add(i);
                    map.put(word1,list);
                }
            }

            if(words[i].equals(word2)){
                if(map.containsKey(word2)){
                    map.get(word2).add(i);
                }else {
                    List list = new ArrayList<>();
                    list.add(i);
                    map.put(word2,list);
                }
            }
        }

        List<Integer> list1 = map.get(word1);
        List<Integer> list2 = map.get(word2);
        int res = n;
        for(int i=0;i<list1.size();i++){
            for(int j=0;j<list2.size();j++){
                int val = Math.abs(list2.get(j)-list1.get(i));
                res = res>val?val:res;
            }
        }

        return res;
    }
}
